from dataclasses import asdict

from fastapi import APIRouter, Depends
from sqlalchemy import text, select

from app.api.user.services.user_service import UserService
from app.core.dependencies import SessionDep
from app.db.page import page_query_by_sql, page_query
from app.models.users import Users
from app.schemas.base import R, BaseModel
from app.schemas.user_dto import UsersDTO

router = APIRouter(prefix="/user", tags=["user"])


class UserOutDTO(BaseModel):
    id: int
    name: str
    age: int


@router.get("/get", response_model=R)
async def read_users(session: SessionDep, query: str = None):
    session.execute(text("select 1"))
    results = session.execute(
        select(Users).where(Users.id.in_([1, 2, 3]), Users.name == "Jack")).scalars()  # type： ignore
    for user in results:
        # print(dataclasses.is_dataclass(user))
        print(user.to_dict())
        print(asdict(user))
        print(UsersDTO(**asdict(user)))

    query_sql = """
        select * from users where id=:id
    """
    pagination = page_query_by_sql(
        session,
        query_sql=query_sql,
        page_num=1,
        page_size=10,
        params={"id": 1},
        cls=UsersDTO
    )
    print(pagination)

    statement = select(Users).where(Users.id.in_([1, 2, 3]))
    pagination = page_query(
        session,
        statement=statement,
        page_num=1,
        page_size=10,
        cls=UsersDTO
    )
    print(pagination)

    # 查询结果为字典类型
    # .mappings().first() 不存在时返回 None
    # .mappings().fetchone() 不存在时返回 None
    # .mappings().one_or_none() 不存在时返回 None
    # .mappings().one() 不存在时抛出异常
    # .mappings().all() 不存在时返回空列表
    # .mappings().fetchall() 不存在时返回空列表
    # results = session.execute(text("select * from users where id=:id"), {"id": 111}).mappings().fetchall()
    # print(results)

    # user = Users(id=14, name="admin", age=25)
    # session.add(user)
    # session.commit()

    return R.ok(data={
        "id": 1,
        "name": "admin",
        "email": "eyoungshieh1992@qq.com",
        "age": 25,
        "query": query
    })


@router.get("/get/user")
async def get_user_by_name(user_service: UserService = Depends(), name: str = None):
    return await user_service.get_user_by_name(name)
